/* eslint-disable array-callback-return */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { isElementSame } from '@ibiz-template/core';
import { TreeController } from '@ibiz-template/runtime';

export class CheckinPeopleTreeController extends TreeController {
  /**
   * @description 数组去重
   * @protected
   * @param {string[]} arr1
   * @param {string[]} arr2
   * @returns {*}
   * @memberof CheckinPeopleTreeController
   */
  protected containsAll(arr1: string[], arr2: string[]): boolean {
    const set = new Set(arr1);
    return arr2.every(item => set.has(item));
  }

  /**
   * @description 设置选中数据
   * @param {{ _id: string }[]} selection
   * @memberof CheckinPeopleTreeController
   */
  setSelection(selection: IData[]): void {
    const selectionIds = selection.map(item => item._id);
    const filterArr = this.state.items.filter(item =>
      selectionIds.includes(item._id),
    );
    const leafKeys = filterArr.filter(item => item._leaf).map(item => item._id);
    const filterKeys: string[] = [];
    filterArr.forEach(item => {
      // 非子节点且展开时计算，当其子项全被选中时需排除自身
      if (!item._leaf && item._children && item._children.length) {
        const expanded = this.state.expandedKeys.includes(item._id);
        const childrenKeys = item._children.map((x: IData) => x._id);
        if (expanded) {
          if (this.containsAll(leafKeys, childrenKeys)) {
            filterKeys.push(item._id);
          }
        } else {
          filterKeys.push(...childrenKeys);
        }
      }
    });
    const tempItems: IData[] = filterArr
      .filter(item => !filterKeys.includes(item._id))
      .map(x => {
        Object.assign(x, { type: x._deData?.type });
        return x;
      });
    const { selectedData } = this.state;
    // 检查新的选中数据和旧的是否一致，不一致才变更。
    if (!isElementSame(selectedData, selection)) {
      this.state.selectedData = tempItems as any[];
      this._evt.emit('onSelectionChange', {
        data: selection,
      });
    }
    // 根据数据计算工具栏权限和状态
    const data = selection?.[0];
    this.batchToolbarController?.calcButtonState(
      data,
      this.model.appDataEntityId,
      { view: this.view, ctrl: this },
    );
    this.quickToolbarController?.calcButtonState(
      data,
      this.model.appDataEntityId,
      { view: this.view, ctrl: this },
    );
  }
}
